package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;


import com.etc.entity.Users;
import com.etc.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UsersController
 */
@WebServlet("/UsersController")
@MultipartConfig
public class UsersController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserServiceImpl service= new UserServiceImpl();  
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UsersController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置请求编码,位置需要放到获取值的前面
	/*	request.setCharacterEncoding("utf-8");*/
		//获取参数 参数名op的值如果是等于query才做查询
		String op=request.getParameter("op");
		//提升:加入session的判断:从session中获取用户登录的信息,如果有,才能执行查询,添加等等的操作
		HttpSession session = request.getSession();
		Object object = session.getAttribute("users");
		if (object != null) {//如果session中用户信息不为空,才能查询...
			//管理员登录后执行的操作
			adminOp(op,request,response);
			
		}else if("login".equals(op)) {
			//管理员的登录功能
			adminLogin(op,request,session,response);
			
		}else if("frontlogin".equals(op)) {
			//普通用户的登录
			frontLogin(op,request,session,response);
			
		}else if("frontExit".equals(op)) {
			//普通用户退出,注销,清除session中用户信息
			frontExit(op,request,session,response);
			
		}else if("register".equals(op)) {
			//普通用户注册
			register(op,request,session,response);
			
		}else if("checkName".equals(op)) {
			//普通用户验证用户名是否可用
			checkName(op,request,session,response);
			
		}else {
			//访问的时候发现没有登录,跳转到登陆页面去
			response.sendRedirect("mvc/login.jsp");
		}
		
	}

	private void checkName(String op, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		// 获取用户名
		String uname = request.getParameter("uname");
		//调用判断用户名的方法
		boolean flag = service.getUserByName(uname);
		if (flag) {
			response.getWriter().print("用户名已存在");
		}else {
			response.getWriter().print("可用");
		}
		
	}

	private void register(String op, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		//执行注册功能
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		//接收文件组件
		Part part = request.getPart("userImg");
		//是否有上传文件
		if(part.getSize()==0) {
			//调用业务层添加用户
			service.addUsers(new Users(userName,userPwd,1,1,null));
			//注册成功前往首页
			response.getWriter().print("<script>alert('注册成功');location.href='front/home.jsp'</script>");
		}else {
			//创建目录,文件存储位置
			File file = new File("C:\\Users\\89728\\Desktop\\新建文件夹");
			if (!file.exists()) {
				//创建目录
				file.mkdir();
			}
			//3.获取文件的真实名
			//System.out.println(part.getName());  myfile
			//通过请求头获取文件真实名
			String header = part.getHeader("content-disposition");
			String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
			System.out.println("文件的真实名"+realName);
			
			//为了文件名重复,在文件名前面计入UUID唯一标志符
			UUID uuid = UUID.randomUUID();
			String newrealName=uuid+realName;
			
			//4.文件全路径
			String filePath="C:\\Users\\89728\\Desktop\\新建文件夹\\"+newrealName;
			//5.真正将文件写入本地
			part.write(filePath);
			//调用注册方法
			boolean flag = service.registerUser(userName, userPwd, newrealName);
			if (flag) {
				//注册成功前往首页
				response.getWriter().print("<script>alert('注册成功');location.href='front/home.jsp'</script>");
			}
		}
		
	}

	private void frontExit(String op, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException {
		//1.普通用户退出,注销,清除session中用户信息
		request.getSession().removeAttribute("frontUser");
		//2.重定向
		response.sendRedirect("front/home.jsp");
		
	}

	private void frontLogin(String op, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("执行了frontLogin");
		//1.获取用户输入的用户名与密码
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		//2.调用业务层
		Users user = service.login(uname, upwd);
		System.out.println("用户是"+user);
		//3.判断用户是否存在
		if (user!=null) {
			//4.判断状态与等级是普通用户
			if(user.getUserStatus()==1 && user.getUserLevel()==1) {
				//5.把用户信息存储到session
				HttpSession session2 = request.getSession();
				session2.setAttribute("frontUser", user);
				//6.转发
				request.getRequestDispatcher("ArticleController?op=frontQuery").forward(request, response);
			}
			
		}else {
			//7.没有这个人,返回首页
			response.sendRedirect("front/home.jsp");
		}
		
	}

	private void adminLogin(String op, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws ServletException, IOException {
		//登录
		//得到用户输入的用户名和密码
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");
		//调用业务层的登录方法
		Users users = service.login(userName, userPwd);
		if (users!=null) {
			//用户名和密码正确
			//只有管理员登录才能访问后台管理界面,需判断其状态==1和等级==2管理员
			if(users.getUserStatus()==1 && users.getUserLevel()==2) {
				//判断用户是否记住密码
				String reme=request.getParameter("remember-me"); 
				if(reme!=null) {
					System.out.println("用户选择记住密码"+reme);
					//存
					Cookie cookie1 = new Cookie("username", userName);
					Cookie cookie2 = new Cookie("userpwd", userPwd);
					Cookie cookie3 = new Cookie("checked", "checked");//选中状态
					
					response.addCookie(cookie1);
					response.addCookie(cookie2);
					response.addCookie(cookie3);
				}
				
				//提升->加入访问控制:登录成功后要将用户登录信息存储在session中
				HttpSession session1 = request.getSession();
				session1.setAttribute("users", users);
				//跳转到后台管理页面
				request.getRequestDispatcher("mvc/showArticles.jsp").forward(request, response);
			}
		}else {
			//用户名和密码错误,跳转到登录页面去
			//1.转发
			//2.重定向
			response.sendRedirect("mvc/login.jsp");
		}
		
	}

	private void adminOp(String op,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if("query".equals(op)) {
			//调用查询方法
			List<Users> list = service.getUsers();
			//存储到request作用域
			request.setAttribute("list", list);
			//forward转发
			request.getRequestDispatcher("mvc/showUsers.jsp").forward(request, response);
		}else if("add".equals(op)) {
			//获取用户输入的用户名与密码
			String username = request.getParameter("username");
			String userpwd = request.getParameter("userpwd");
			//获取到的value是字符串类型,需要转型
			int userstate =Integer.parseInt(request.getParameter("userstate")) ;
			int userlevel = Integer.parseInt(request.getParameter("userlevel"));
			Users users = new Users(username, userpwd, userstate, userlevel);
			//调用service添加的方法
			boolean flag=service.addUsers(users);
			//forward转发 转发到servlet而不是jsp 
			request.getRequestDispatcher("UsersController?op=query").forward(request, response);
		}else  if("login".equals(op)){
			//重复登录的情况,跳转到首页
			request.getRequestDispatcher("ArticleController?op=query").forward(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
